﻿/*
    Copyright (c) 2009 Chris Umbel

    Permission is hereby granted, free of charge, to any person obtaining a 
	copy of this software and associated documentation files (the "Software"), 
	to deal in the Software without restriction, including without limitation 
	the rights to use, copy, modify, merge, publish, distribute, sublicense, 
	and/or sell copies of the Software, and to permit persons to whom the Software 
	is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all 
	copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 
	FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 
	COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
	IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ReportingServices.DataProcessing;
using System.IO;

namespace CouchDBExtension
{
    public class CouchDBReader : IDataReader
    {
        private StreamReader _couchDataStreamReader;
        private char _current;
        private int _depth = 0;
        private bool _parsingValue = false;
        private Dictionary<string, object> _rowData = new Dictionary<string, object>();
        private int _rowNumber = 0;

        public CouchDBReader(Stream stream)
        {
            _couchDataStreamReader = new StreamReader(stream);

            InitializeStream();
        }

        /* set up stream */
        private void InitializeStream()
        {
            AdvanceReader();

            /* skip meta data at the begining of the response*/
            HandleCurley();

            while (_current != '{' && !_couchDataStreamReader.EndOfStream)
            {
                AdvanceReader();
            }

            HandleCurley();

            /* read the first line to initialize the column data */
            this.Read();
        }

        /* determing the ordinality of a field name */
        public int GetOrdinal(string name)
        {
            int ordinal = -1;
            int i;

            for (i = 0; i < _rowData.Keys.Count; i++)
            {
                if (name.Equals(_rowData.Keys.ElementAt(i)))
                    ordinal = i;
            }

            return ordinal;
        }

        public object GetValue(int i)
        {
            return _rowData[GetName(i)];
        }

        public int FieldCount { 
            get 
            { 
                return _rowData.Count; 
            } 
        }

        public string GetName(int i) 
        { 
            return _rowData.Keys.ElementAt(i); 
        }

        public Type GetFieldType(int i)
        {
            return _rowData[GetName(i)].GetType();
        }

        private void AdvanceReader()
        {
            _current = (char)_couchDataStreamReader.Read();
        }

        /* a key value pair has been found, store it */
        private void HandleFieldData(string fieldName, object value)
        {
            if (!_rowData.ContainsKey(fieldName))
                _rowData.Add(fieldName, value);
            else
                _rowData[fieldName] = value;
        }

        /* handle the detection of a JSON string in a couchdb response stream */
        private string HandleString()
        {
            StringBuilder token = new StringBuilder();

            /* skip first " */
            AdvanceReader();

            while (!_couchDataStreamReader.EndOfStream && _current != '"')
            {
                token.Append(_current);
                AdvanceReader();
            }

            AdvanceReader();

            _parsingValue = !_parsingValue;

            return token.ToString();
        }

        /* handle the detection of a numeric JSON value  in a couchdb response stream*/
        private double HandleNumber()
        {
            StringBuilder token = new StringBuilder();

            while (!_couchDataStreamReader.EndOfStream && (char.IsNumber(_current) || _current == '.'))
            {
                token.Append(_current);
                AdvanceReader();
            }

            _parsingValue = !_parsingValue;

            return double.Parse(token.ToString());
        }

        /* handle the detection of a curley bracket */
        private bool HandleCurley()
        {
            bool endOfRow = false;

            _depth += (_current == '{') ? 1 : -1;
            /* determine if we're closing out a document */
            endOfRow = (_current == '}' && _depth == 1);
            /* if we're changing levels we can't be parsing a value next */
            _parsingValue = false;
            AdvanceReader();

            return endOfRow;
        }

        /* read a row from a couchdb response stream */
        public bool Read()
        {
            bool endOfRow = false;

            string fieldName = string.Empty;
            object value = string.Empty;

            while (_rowNumber != 1 /* first row is read once by constructor for field detection, 
                                    * don't advance the stream on the second read of the first row */ && 
                !endOfRow && !_couchDataStreamReader.EndOfStream)
            {
                /* see if we've found a JSON string */
                if (_current == '"')
                {
                    if (!_parsingValue)
                        fieldName = HandleString();
                    else
                    {
                        value = HandleString();
                        HandleFieldData(fieldName, value);
                    }
                }
                /* see if we've found a number */
                else if (char.IsNumber(_current))
                {
                    value = HandleNumber();
                    HandleFieldData(fieldName, value);
                }
                /* see if we've found a curley bracket */
                else if (_current == '{' || _current == '}')
                    endOfRow = HandleCurley();
                else
                    AdvanceReader();
            }

            _rowNumber++;

            return !_couchDataStreamReader.EndOfStream;
        }

        public void Dispose()
        {
            _couchDataStreamReader.Close();
        }
    }
}
